package com.bosicloud.cmb.ibp.aws.adapter.component.notify.impl;

import com.alibaba.fastjson.JSONObject;
import com.bosicloud.cmb.ibp.QueueNames;
import com.bosicloud.cmb.ibp.aws.adapter.commom.model.CFNotifyMessage;
import com.bosicloud.cmb.ibp.aws.adapter.component.notify.NotifyService;
import com.bosicloud.cmb.ibp.commom.dto.exchange.ExchangeAction;
import com.bosicloud.cmb.ibp.commom.dto.exchange.ExchangeMessage;
import com.bosicloud.cmb.ibp.commom.exception.BusinessException;
import com.bosicloud.cmb.ibp.commom.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Optional;
import java.util.Properties;

/**
 * @author Jack Peng / ziliang.peng@bosicloud.com
 */
@Slf4j
public class NotificationImpl implements NotifyService {

    private String content;
    private QueueMessagingTemplate template;
    private QueueNames queueNames;

    private final String regex = "^.|.$";

    public NotificationImpl(String content,
                            QueueMessagingTemplate template,
                            QueueNames queueNames) {
        this.content = content;
        this.template = template;
        this.queueNames = queueNames;
    }

    @Override
    public void exec() {

        JSONObject obj = JSONObject.parseObject(content);

        Optional<String> message = Optional.ofNullable(obj.getString("Message"));

        if(message.isPresent() && !message.get().isEmpty()) {

            try {

                Properties properties = new Properties();
                properties.load(IOUtils.toInputStream(message.get()));

                if(log.isDebugEnabled()) {

                    StringBuilder sb = new StringBuilder();
                    Enumeration<Object> keys = properties.keys();

                    sb.append("\n >> --------------------------------------------------\n");
                    while (keys.hasMoreElements()) {
                        String key = keys.nextElement().toString();
                        sb.append(String.format(" >> %s : %s \n", key, properties.getProperty(key, "")));
                    }
                    sb.append(" >> --------------------------------------------------\n");

                    log.debug(sb.toString());
                }

                Optional<String> token = Optional.ofNullable(properties.getProperty("ClientRequestToken"));

                if(token.isPresent() && !token.get().isEmpty()) {

                    CFNotifyMessage message1 = CFNotifyMessage.builder().
                            clientRequestToken(properties.getProperty("ClientRequestToken", "").replaceAll(regex,"")).
                            logicalResourceId(properties.getProperty("LogicalResourceId", "").replaceAll(regex,"")).
                            stackName(properties.getProperty("StackName", "").replaceAll(regex,"")).
                            namespace(properties.getProperty("Namespace", "").replaceAll(regex,"")).
                            resourceProperties(properties.getProperty("ResourceProperties", "").replaceAll(regex,"")).
                            timestamp(properties.getProperty("Timestamp", "").replaceAll(regex,"")).
                            resourceStatus(properties.getProperty("ResourceStatus", "").replaceAll(regex,"")).
                            resourceType(properties.getProperty("ResourceType", "").replaceAll(regex,"")).
                            resourceStatusReason(properties.getProperty("ResourceStatusReason", "").replaceAll(regex,"")).
                            stackId(properties.getProperty("StackId", "").replaceAll(regex,"")).
                            eventId(properties.getProperty("EventId", "").replaceAll(regex,"")).
                            physicalResourceId(properties.getProperty("PhysicalResourceId", "").replaceAll(regex,"")).
                            build();

                    template.convertAndSend(queueNames.getResponseMicroPlatform(),
                            ExchangeMessage.builder()
                                    .Action(ExchangeAction.MICROPLATFORM_RESPONSE)
                                    .data(message1)
                                    .build());

                }

            } catch (IOException e) {
                throw new BusinessException("消息转换失败.");
            }

        } else {
            throw new BusinessException("NotificationImpl 空消息.");
        }

    }
}
